var express = require('express');
var router = express.Router();
const {userModel, listModel} = require("../db/index");

router.get('/collect', async (req, res) => {
  try {
      // 从请求头获取用户名和密码
      const { username, password } = req.query;
      
      if (!username || !password) {
          return res.status(400).json({
              code: 400,
              msg: '需要提供用户名和密码'
          });
      }

      // 查找用户
      const user = await userModel.findOne({username, password});
      
      if (!user) {
          return res.status(404).json({
              code: 404,
              msg: '用户不存在或密码错误'
          });
      }

      // 查询该用户的收藏商品
      const data = await listModel.find({
          user_id: user._id,
          collect: true
      });
      
      res.json({
        code: 200,
        data: data,    
      });
  } catch (error) {
      console.error(error);
      res.status(500).json({
          code: 500,
          msg: '服务器错误'
      });
  }
});

router.post('/uncollect', async (req, res) => {
  try {
    const { userId, itemId } = req.body;
    
    // 更新商品的收藏状态 
    const result = await listModel.updateOne(
      { _id: itemId, user_id: userId },
      { $set: { collect: false } }
    );   
    
    if (result.modifiedCount === 0) {
      return res.status(404).json({
        code: 404,
        msg: '未找到收藏记录'
      });
    }
    
    res.json({
      code: 200,
      msg: '取消收藏成功'
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({
      code: 500,
      msg: '服务器错误'
    });
  }
});




module.exports = router;
